import { NextRequest, NextResponse } from 'next/server';
import { initializeDatabase, createMessage, getMessages, Message } from '@/lib/database';
import { withCors } from '@/lib/cors';

// 初始化数据库
let dbInitialized = false;
async function ensureDatabaseInitialized() {
  if (!dbInitialized) {
    await initializeDatabase();
    dbInitialized = true;
  }
}

// POST /api/messages - 创建新消息
async function handlePOST(request: NextRequest) {
  try {
    await ensureDatabaseInitialized();

    const body = await request.json();
    const { sessionId, role, content, metadata } = body;

    if (!sessionId || !role || !content) {
      return NextResponse.json(
        { error: '缺少必要参数: sessionId, role, content' },
        { status: 400 }
      );
    }

    const messageId = `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    const message: Omit<Message, 'createdAt'> = {
      id: messageId,
      sessionId,
      role,
      content,
      timestamp: new Date().toISOString(),
      metadata
    };

    await createMessage(message);

    return NextResponse.json({ message });
  } catch (error) {
    console.error('创建消息失败:', error);
    return NextResponse.json(
      { error: '创建消息失败' },
      { status: 500 }
    );
  }
}

// 导出带 CORS 支持的处理器
export const POST = withCors(handlePOST);
